package com.ssdp.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * @author syo 2319615164@qq.com
 * @description Id生成器
 * @date 2024/3/14
 * @Copyright syo
 */
@Component
@SuppressWarnings("all")
public class RedisIdWorker {
    // 开始的时间戳，可随意选一个作为随机种子
    private static final long BEGIN_TIMESTAMP = 1640995200L;

    private static final long BIT_MOVE_COUNTS = 32;

    private StringRedisTemplate stringRedisTemplate;

    /**
     * 构造函数注入
     * @param stringRedisTemplate redis客户端
     */
    public RedisIdWorker(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    // 业务名称
    public long nextId(String keyPrefix) {
        // 1. 生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowEpochSecond = now.toEpochSecond(ZoneOffset.UTC);
        long timestamp = nowEpochSecond - BEGIN_TIMESTAMP;

        // 2. 生成序列号
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));

        // 3.自增长数字
        long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + date);

        // 4. 拼接返回
        return timestamp << BIT_MOVE_COUNTS | count;
    }

}
